package com.campus.common;

/**
 * @desc:
 * @author: Ping
 * @date: 2024/11/5 10:18
 */

import com.campus.domain.Dto.UserLoginDto;
import com.campus.domain.TSysRole;
import com.campus.common.BusinessConstants;
import com.campus.exception.TokenGenerateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.stream.Collectors;

import static com.campus.common.BusinessConstants.*;

/**
 * TOKEN rule:
 *   (1) token = base64(timestamp,username,roleNameStr)
 */
@Slf4j
public class TokenManager {
    private static final String DELIMITER = ",";

    public static String getToken(UserLoginDto user) {
        if (ObjectUtils.isEmpty(user) || ObjectUtils.isEmpty(user.getRoles())) {
            throw new TokenGenerateException() ;
        }
        String val = System.currentTimeMillis()
                + DELIMITER +user.getLoginName()
                + DELIMITER +(user.getRoles().stream()
                .map(TSysRole::getName).collect(Collectors.joining(DELIMITER)));
        log.info("tokenStr: {}", val);
        String token = null ;
        try {
            token = new String(Base64.getEncoder().encode(val.getBytes(BusinessConstants.UTF_ENCODING)));
            log.info("token: {}", token);
        } catch (UnsupportedEncodingException e) {
            throw new TokenGenerateException(e.getMessage()) ;
        }
        return token ;
    }

    public static String[] decodeToken(String token) {
        Assert.notNull(token, "token must not be null");
        String decodedToken = null ;
        try {
            decodedToken = new String(Base64.getDecoder().decode(token.getBytes(BusinessConstants.UTF_ENCODING))) ;
        } catch (UnsupportedEncodingException e) {
            throw new TokenGenerateException(e.getMessage());
        }
        return decodedToken.split(DELIMITER);
    }
    public static boolean isValided(HttpSession session, String token) {
        if (ObjectUtils.isEmpty(token)) {
            return false;
        }
        if (session.getAttribute(TOKEN_KEY) == null ) {
            return false;
        }
        String realToken = (String) session.getAttribute(TOKEN_KEY) ;

        if (!token.equals(realToken)) {
            return false;
        }
        log.info(" Token in session and in request header are equals.") ;
        // token的格式不正确
        String[] decodedToken = decodeToken(token) ;
        log.info(" decoded Token {}, with length {}", decodedToken, decodedToken.length) ;
        if (decodedToken == null || decodedToken.length < 3) {
            return false ;
        }
        String userName = (String) session.getAttribute(USER_KEY) ;
        if (! decodedToken[1].equals(userName)) {
            return false ;
        }
        return true ;
    }

    public static List<String> getRolesFromToken(String token) {
        Assert.notNull(token, "token must not be null");
        String[] tokenSplit = decodeToken(token) ;
        log.info("tokenSplit: {}", tokenSplit);
        return Arrays.asList(tokenSplit).subList(2, tokenSplit.length) ;
    }
}
